library citypicker;

export 'listener/picker_listener.dart';

import 'package:flutter/material.dart';
import 'package:kmxy_base/city_picker/http/http_util.dart';
import 'package:kmxy_base/util/sp_util.dart';

import 'listener/picker_listener.dart';
import 'model/address.dart';
import 'view/city_picker.dart';

/// 外部调用
class CityPicker implements CityPickerListener {
  static final CityPicker getInstance = CityPicker._internal();

  ///工厂构造函数
  factory CityPicker() => getInstance;

  ///构造函数私有化，防止被误创建
  CityPicker._internal();

  /// 展示
  void show({
    required BuildContext context,
    // 0: 省 1: 市  2: 地区 3: 街道
    int currentType = 3,
    AnimationController? animController,
    // 背景透明度
    double opacity = 0.5,
    // 点击外部是否消失
    bool dismissible = true,
    // 高度
    double height = 500.0,
    // 标题高度
    double titleHeight = 50.0,
    // 顶部圆角
    double corner = 20.0,
    // 背景颜色
    Color? backgroundColor,
    // 距离左边的间距
    double paddingLeft = 15.0,
    // 标题组件
    Widget? titleWidget,
    // 选择文字
    String? selectText,
    // 关闭图标组件
    Widget? closeWidget,
    // tab 高度
    double tabHeight = 40.0,
    // 是否显示指示器
    bool showTabIndicator = true,
    // tab 间隔
    double tabPadding = 10.0,
    // 指示器颜色
    Color? tabIndicatorColor,
    // 指示器高度
    double tabIndicatorHeight = 3.0,
    // tab 字体大小
    double labelTextSize = 15.0,
    // tab 选中的字体颜色
    Color? selectedLabelColor,
    // tab 未选中的字体颜色
    Color? unselectedLabelColor,
    // item 头部高度
    double itemHeadHeight = 30.0,
    // item 头部背景颜色
    Color? itemHeadBackgroundColor,
    // item 头部分割线颜色
    Color? itemHeadLineColor,
    // item 头部分割线高度
    double itemHeadLineHeight = 0.1,
    // item 头部文字样式
    TextStyle? itemHeadTextStyle,
    // item 高度
    double itemHeight = 40.0,
    // 索引组件宽度
    double indexBarWidth = 28,
    // 索引组件 item 高度
    double indexBarItemHeight = 20,
    // 索引组件背景颜色
    Color indexBarBackgroundColor = Colors.black12,
    // 索引组件文字样式
    TextStyle? indexBarTextStyle,
    // 列表选中的图标组件
    Widget? itemSelectedIconWidget,
    // 列表选中的文字样式
    TextStyle? itemSelectedTextStyle,
    // 列表未选中的文字样式
    TextStyle? itemUnSelectedTextStyle,
    // 地址初始值
    List<AddressNode>? initialAddress,
    // 地址选择器监听事件
    required Function onData,
  }) {
    _currentType = currentType;
    mOnData = onData;
    showModalBottomSheet<void>(
        context: context,
        backgroundColor: backgroundColor,
        isScrollControlled: true,
        isDismissible: dismissible,
        barrierColor: Colors.black.withOpacity(opacity),
        transitionAnimationController: animController,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(corner),
            topRight: Radius.circular(corner),
          ),
        ),
        builder: (BuildContext context) {
          return CityPickerWidget(
            height: height,
            titleHeight: titleHeight,
            corner: corner,
            backgroundColor: backgroundColor,
            paddingLeft: paddingLeft,
            titleWidget: titleWidget,
            selectText: selectText,
            closeWidget: closeWidget,
            tabHeight: tabHeight,
            showTabIndicator: showTabIndicator,
            tabPadding: tabPadding,
            tabIndicatorColor: tabIndicatorColor,
            tabIndicatorHeight: tabIndicatorHeight,
            labelTextSize: labelTextSize,
            selectedLabelColor: selectedLabelColor,
            unselectedLabelColor: unselectedLabelColor,
            itemHeadHeight: itemHeadHeight,
            itemHeadBackgroundColor: itemHeadBackgroundColor,
            itemHeadLineColor: itemHeadLineColor,
            itemHeadLineHeight: itemHeadLineHeight,
            itemHeadTextStyle: itemHeadTextStyle,
            itemHeight: itemHeight,
            indexBarWidth: indexBarWidth,
            indexBarItemHeight: indexBarItemHeight,
            indexBarBackgroundColor: indexBarBackgroundColor,
            indexBarTextStyle: indexBarTextStyle,
            itemSelectedIconWidget: itemSelectedIconWidget,
            itemSelectedTextStyle: itemSelectedTextStyle,
            itemUnSelectedTextStyle: itemUnSelectedTextStyle,
            initialAddress: initialAddress,
            cityPickerListener: this,
            historyCall: mOnData,
          );
        });
  }

  late Function mOnData;

  /// 0: 省
  /// 1: 市
  /// 2: 地区
  /// 3: 街道
  int _currentType = 3;

  List<AddressNode> _selectProvince = [];
  List<AddressNode> _selectCity = [];
  List<AddressNode> _selectArea = [];
  List<AddressNode> _selectStreet = [];

  /// 选择的地址
  List<AddressNode> get selectAddress =>
      [..._selectProvince, ..._selectCity, ..._selectArea, ..._selectStreet];

  @override
  Future<List<AddressNode>> onDataLoad(
      int index, String code, String name) async {
    if (index == 0) {
      await Future.delayed(const Duration(milliseconds: 200));
      return HttpUtils.getCityData("");
    } else {
      if (_currentType == 0) {
        return Future.value([]);
      } else if (_currentType == 1) {
        if (index == 2) {
          return Future.value([]);
        }
        return HttpUtils.getCityData(name);
      } else if (_currentType == 2) {
        if (index == 3) {
          return Future.value([]);
        }
        return HttpUtils.getCityData(name);
      } else {
        return HttpUtils.getCityData(name);
      }
    }
  }

  String _addressProvince = "请选择省";
  String _addressCity = "请选择市";
  String _addressArea = "请选择地区";
  String _addressStreet = "请选择街道";
  /// 选择的地址
  String get selectAddressStr =>
      "$_addressProvince/$_addressCity/$_addressArea/$_addressStreet";

  // ignore: non_constant_identifier_names
  String SP_CITY_PICKER_HISTORY = 'SP_CITY_PICKER_HISTORY';

  @override
  void onFinish(List<AddressNode> data) async {
    String add = "";
    String code = "";
    for (var node in data) {
      add += "${node.name}/";
      code += "${node.code}/";
    }
    if (_currentType == 0) {
      _addressProvince = add;
      _selectProvince = data;
    } else if (_currentType == 1) {
      _addressCity = add;
      _selectCity = data;
    } else if (_currentType == 2) {
      _addressArea = add;
      _selectArea = data;
    } else {
      _addressStreet = add;
      _selectStreet = data;
    }
    // 加入记录
    String value = '';
    if (add.isNotEmpty) {
      List split = add.split('/');
      value = split[split.length - 2];
    }
    String key = '';
    if (code.isNotEmpty) {
      List split = code.split('/');
      key = split[split.length - 2];
    }
    List list = await SpUtil.getList(SP_CITY_PICKER_HISTORY) ?? [];
    if (list.length > 5) {
      list.removeAt(list.length - 1);
    }

    Map dataMap = {
      'keys': code.substring(0, code.length - 1),
      'values': add.substring(0, add.length - 1),
      'key': key,
      'value': value,
    };
    bool isJoin = true;
    for (Map item in list) {
      if (item['key'] == dataMap['key']) {
        isJoin = false;
        break;
      }
    }
    if (isJoin) {
      list.insert(0, dataMap);
    }
    SpUtil.setList(SP_CITY_PICKER_HISTORY, list);
    mOnData(dataMap);
  }
}
